<template>
  <div>
    <!-- 主要操作区域以card样式出现 -->
    <el-card shadow="always" :body-style="{ padding: '5px 20px 15px 20px' }">
      <!-- 主要操作区域 -->
      <div class="main_area">
        <!-- 查询区域 -->
        <div class="search_area" ref="search_area">
          <div style="padding-bottom: 10px">
            <el-menu :default-active="active" router class="el-menu-tab" @select="selectApp" mode="horizontal">
              <el-menu-item v-for="item in app_list" :key="item.app_id" :index="item.url">
                <router-link :to="item.url"> {{ item.application_name }}</router-link>
              </el-menu-item>
            </el-menu>
          </div>
        </div>
        <!-- 操作区域 -->
        <div class="action_area" ref="action_area">
          <vxe-toolbar ref="xToolbarSysMenu" :size="formSize" :custom="custom" :refresh="{ query: index }"
                       class-name="x-toolbar">
            <template #buttons>
              <div class="toolbar-button">
                <el-button id="addApi" type="success" :size="formSize" icon="el-icon-plus" @click="addApi()">创建
                </el-button>
                <el-button id="deleteMenu" type="danger" :size="formSize" icon="el-icon-delete" @click="deleteMenu()">
                  卸载
                </el-button>
                <el-button id="field" type="warning" :size="formSize" icon="el-icon-plus"
                           :disabled="selectRow && !selectRow.table_name" @click="field">字段管理
                </el-button>
                <el-button id="action" type="warning" :size="formSize" icon="el-icon-plus"
                           :disabled="selectRow && !selectRow.table_name" @click="action">方法管理
                </el-button>
                <el-button id="create" type="info" :size="formSize" icon="el-icon-edit-outline"
                           :disabled="selectRow && !selectRow.table_name" @click="create">生成代码
                </el-button>

                <el-select class="hidden-sm-and-down form-item-margin" :size="formSize" @change="selectConnect"
                           v-model="connect" placeholder="请选择链接库">
                  <el-option v-for="item in connects" :key="item" :label="item" :value="item"></el-option>
                </el-select>
                <el-select id="createByTable" class="hidden-sm-and-down form-item-margin" :size="formSize" v-model="tablename"
                           placeholder="请选择数据表">
                  <el-option v-for="(item,i) in tableList" :key="i" :label="item" :value="item"></el-option>
                </el-select>
                <el-button class="hidden-sm-and-down" type="primary" :size="formSize" icon="el-icon-check"
                           @click="createByTable">根据表生成
                </el-button>

                <el-button id="synCopy" class="hidden-md-and-down" type="warning" :size="formSize" icon="el-icon-edit-outline"
                           :disabled="selectRow && !selectRow.copy_from" @click="synCopy">同步复制
                </el-button>
                <el-button id="exportMenuSQL" class="hidden-md-and-down" type="success" :size="formSize" icon="el-icon-download"
                           :disabled="selectRow && !selectRow.table_name" @click="exportMenuSQL">导出SQL
                </el-button>
                <el-button id="getDoc" class="hidden-md-and-down" type="danger" :size="formSize" icon="el-icon-notebook-2"
                           @click="getDoc(app_id)">生成文档
                </el-button>

              </div>
            </template>
          </vxe-toolbar>
        </div>
        <!-- 表格区域 -->
        <div class="table_area_menu" ref="table_area_menu">
          <vxe-table
              ref="xTable" id="xTable" border height="100%" :data="list" :loading="loading" :size="formSize"
              v-if="list" :keyboard-config="keyboardConfig" :custom-config="customConfig"
              :column-config="columnConfig" :row-config="rowConfig"
              :tree-config="treeConfig" :edit-config="editConfig"
              :radio-config="radioConfig"
              @radio-change="radioChange">
            <template>
              <vxe-column type="radio" width="40"></vxe-column>
              <vxe-column title="编号" field="menu_id" width="60" min-width="60" show-overflow></vxe-column>
              <vxe-column title="名称" field="title" tree-node min-width="160" show-overflow></vxe-column>
              <vxe-column title="控制器" field="controller_name" min-width="140" show-overflow></vxe-column>
              <vxe-column title="表名" field="table_name" min-width="140" show-overflow></vxe-column>
              <vxe-column title="生成" field="create_code" width="80" align="center" min-width="80" show-overflow>
                <template #default="{ row }">
                  <el-switch :active-value="1" :inactive-value="0" @change="update(row,'create_code')"
                             v-model="row.create_code"></el-switch>
                </template>
              </vxe-column>
              <vxe-column title="建表" field="create_table" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :size="formSize" :type="row.create_table=='1'?'success':'info'" effect="dark">
                    {{ row.create_table == '1' ? '是' : '否' }}
                  </el-tag>
                </template>
              </vxe-column>
              <vxe-column title="排序" field="sortid" width="80" :edit-render="{}">
                <template #edit="{ row }">
                  <el-input :size="formSize" placeholder="排序" @blur.stop="update(row,'sortid')"
                            v-model="row.sortid"></el-input>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="200" :key="Math.random()" align="center"
                          :fixed="$store.getters.device !== 'mobile' ? 'right' : ''">
                <template #default="{ row }">
                  <el-button :size="formSize" @click="editorApi(row)" type="primary"><i class="el-icon-edit-outline"/>修改
                  </el-button>
                  <el-button :size="formSize" @click="deleteMenu(row)" type="danger"><i class="el-icon-delete"/>卸载
                  </el-button>
                </template>
              </vxe-column>
            </template>
          </vxe-table>
        </div>
      </div>
    </el-card>
    <div>

      <!--添加-->
      <ApiAdd
          :show.sync="dialog.addApiDialogStatus"
          :app_id="app_id"
          :list="listTree"
          :connects="connects"
          :size="formSize"
          @refesh_list="index"></ApiAdd>

      <!--修改-->
      <ApiUpdate
          :show.sync="dialog.updateApiDialogStatus"
          :info="info"
          :app_id="app_id"
          :list="listTree"
          :connects="connects"
          :size="formSize"
          @refesh_list="index"></ApiUpdate>

    </div>

    <!-- 操作向导 -->
    <v-tour name="myApiTour" :steps="steps" :callbacks="callbacks" :options="myOptions"></v-tour>

  </div>

</template>
<script>
import {
  getApiList,
  getMenuInfo,
  getTableList,
  updateMenuExt,
  deleteMenu,
  create,
  createByTable,
  copyMenu,
  getDoc,
  exportMenuSQL,
  synCopy,
} from '../sys'


import ApiAdd from './api/Add.vue'
import ApiUpdate from './api/Update.vue'
import mixinVexTable from "@/mixin/vxeTable"

export default {
  name: 'Menu',
  mixins: [mixinVexTable],
  components: {ApiAdd, ApiUpdate},
  data() {
    return {
      dialog: {
        addAdminDialogStatus: false,
        updateAdminDialogStatus: false,
        addApiDialogStatus: false,
        updateApiDialogStatus: false,
      },
      listTree: [],
      row: {},
      menu_id: null,
      connects: [],
      connect: '',
      tablename: '',
      tableList: [],
      app_id: '2',
      appid: null,
      app_type: '2',
      app_list: [],
      copy_app_list: [],
      info: {},
      loading: false,
      active: '/admin/Menu/index.html?app_id=2&app_type=2',

      // 表格配置
      keyboardConfig: {
        isArrow: true,
      },
      customConfig: {
        storage: true,
      },
      columnConfig: {
        isCurrent: true,
        isHover: true,
        resizable: true,
      },
      rowConfig: {
        keyField: 'menu_id',
        isCurrent: true,
        isHover: true,
      },
      radioConfig: {
        trigger: 'row'
      },
      editConfig: {
        enabled: true,
        trigger: 'dblclick',
        mode: 'cell',
      },
      treeConfig: {
        transform: true,
        rowField: 'menu_id',
        parentField: 'pid',
        trigger: 'row',
        reserve: true,
        expandAll: true,
      },

      tagsLocal: {
        path: null,
        query: null,
        fullPath: null,
        title: null,
        meta: {
          title: null
        },
        name: null
      },
      // 向导的步骤定义，分别定义一个原生，标题，提示内容，支持html代码
      steps: [
        {
          target: '#addApi',
          header: {
            title: '创建菜单',
          },
          content: `<div class="tour">点击按钮创建API菜单项，如果是后端已经创建了同表菜单，请直接从管理系统复制到本应用即可；</div>`
        },
        {
          target: '#deleteMenu',
          header: {
            title: '删除菜单',
          },
          content: `<div class="tour">删除菜单时，需要注意，如果菜单配置“建表”为开启状态，则删除菜单时，会将数据库表一并删除！</div>`
        },
        {
          target: '#field',
          header: {
            title: '管理字段',
          },
          content: `<div class="tour">选中菜单项后，可以管理此菜单的字段！</div>`
        },
        {
          target: '#action',
          header: {
            title: '管理方法',
          },
          content: `<div class="tour">选中菜单项后，可以管理此菜单的方法！</div>`
        },
        {
          target: '#create',
          header: {
            title: '生成代码',
          },
          content: `<div class="tour">选中菜单项后，点击此按钮可以生成菜单的前后端代码；</div>`
        },
        {
          target: '#createByTable',
          header: {
            title: '根据表生成',
          },
          content: `<div class="tour">点击左侧下拉框选中数据源，点击此处的下拉框选择数据库表，点击右侧按钮，就可以根据数据库表的定义，自动生成菜单；</div>`
        },
        {
          target: '#synCopy',
          header: {
            title: '同步复制',
          },
          content: `<div class="tour">如果某菜单是通过复制菜单创建的，则此按钮可用，用于将父菜单的变化，同步到本菜单；</div>`
        },
        {
          target: '#exportMenuSQL',
          header: {
            title: '导出SQL',
          },
          content: `<div class="tour">选中任意菜单项，都可以将此菜单对应的菜单、字段、方法对应的SQL语句和此表的DLL语句导出到一个文件中；</div>`
        },
        {
          target: '#getDoc',
          header: {
            title: '生成API文档',
          },
          content: `<div class="tour">点击按钮可以生成前端API接口的文档，访问文档，请打开【API文档】菜单；</div>`
        },
      ],
    };
  },
  activated() {
    // 页面每次载入都执行
    this.app_type = this.$route.query.app_type ? this.$route.query.app_type : '2'
    this.app_id = this.$route.query.app_id ? this.$route.query.app_id : '2'
    if (this.app_id) {
      this.active = this.$route.fullPath
    } else {
      this.app_id = '2'
      this.active = '/admin/Menu/index.html?app_id=2&app_type=2'
    }
    this.index()
    // 默认关闭向导，如需开启请去掉下面的注释
    // 第一次打开软件自动启动向导，点击跳过或者完成以后，则不再启动向导
    // if (!localStorage.getItem('finish_api_tour')) {
    //   setTimeout(()=>{
    //     this.$tours['myApiTour'].start()
    //   },2000)
    // }
  },
  mounted() {
    this.$nextTick(() => {
      var searchHeight = this.$refs.search_area.offsetHeight
      var actionHeight = this.$refs.action_area.offsetHeight
      var height = document.body.offsetHeight - this.headerHeight - this.tagHeight - searchHeight - actionHeight - 85
      this.$refs.table_area_menu.style.height = height + 'px';
    });
  },
  methods: {
    // 选中行
    radioChange({row}) {
      // console.log(row)
      // app_id 的数组
      this.menu_id = row.menu_id
      // 所选行数据
      this.selectRow = row
      // 是否是单选
      this.single = row.menu_id ? true : false
      // 是否是多选
      this.multiple = false
    },
    // 载入菜单
    index() {
      this.loading = true
      getApiList({app_id: this.app_id}).then(res => {
        this.list = res.list
        this.listTree = res.listTree
        this.connects = res.connects
        this.connect = res.defaultConnect
        this.tableList = res.tableList
        this.app_list = res.app_list
        this.copy_app_list = res.app_list.filter(item => item.app_type !== 3)
        this.loading = false
      })
    },
    // 添加API
    addApi() {
      this.selectRow = null
      this.dialog.addApiDialogStatus = true
    },
    // 编辑API
    editorApi(row) {
      this.selectRow = row
      getMenuInfo({menu_id: row.menu_id}).then(res => {
        this.dialog.updateApiDialogStatus = true
        this.info = res.data
      })
    },
    // 导航到字段管理
    field() {
      Object.assign(this.tagsLocal, this.$route)
      this.$store.dispatch('deletetag', this.tagsLocal)
      let app_type = this.$route.query.app_type ? this.$route.query.app_type : this.app_type
      this.$router.push({
        path: '/admin/Field/index.html',
        query: {app_id: this.app_id, app_type: app_type, menu_id: this.menu_id, url: '/admin/Api/index.html'},
      })
    },
    // 导航到方法管理
    action() {
      Object.assign(this.tagsLocal, this.$route)
      this.$store.dispatch('deletetag', this.tagsLocal)
      let app_type = this.$route.query.app_type ? this.$route.query.app_type : this.app_type
      this.$router.push({
        path: '/admin/Action/index.html',
        query: {app_id: this.app_id, app_type: app_type, menu_id: this.menu_id, url: '/admin/Api/index.html'},
      })
    },
    // 选则数据库链接
    selectConnect(val) {
      getTableList({connect: this.connect}).then(res => {
        this.tableList = res.data
      })
    },
    // 选择菜单
    selectApp(index) {
      this.list = []
      this.app_id = this.$MyUtils.param2Obj(index).app_id
      this.app_type = this.$MyUtils.param2Obj(index).app_type
      this.active = index
      this.index()
    },
    // 生成API文档
    getDoc(app_id) {
      var content = "请确认成功安装apidoc指定版本【npm install apidoc@0.50.5 -g】，并确认其可用性；";
      content += "<br>";
      content += "请输入文档绑定域名，如果留空，则默认使用当前开发环境域名"
      content += "<br>";
      content += "例如：https://api.simplest.net.cn"
      this.$prompt(content, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true
      }).then(({value}) => {
        this.loading = true
        getDoc({app_id: app_id, domain: value}).then(res => {
          if (res.status == 200) {
            this.$confirm(res.msg, '提示', {
              showCancelButton: false,
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true
            })
          }
          this.loading = false
        }).catch(() => {
          this.loading = false
        });
      }).catch(() => {
      });
    },
    // 删除菜单
    deleteMenu(row) {
      this.$MyUtils.confirm({content: '确定要卸载吗?'}).then(() => {
        deleteMenu({menu_id: row.menu_id}).then(res => {
          this.$message({message: '操作成功', type: 'success'})
          this.$refs.xTable.remove(row)
        })
      }).catch(() => {
      })
    },
    // 行内修改
    update(row, field) {
      updateMenuExt({menu_id: row.menu_id, [field]: row[field]}).then(res => {
        this.$message({message: '操作成功', type: 'success'})
      })
    },
    // 生成代码
    create() {
      this.$MyUtils.confirm({content: '确定生成吗?'}).then(() => {
        create({menu_id: this.menu_id}).then(res => {
          this.$message({message: '操作成功', type: 'success'})
        })
      }).catch(() => {
      })
    },
    // 导出SQL
    exportMenuSQL() {
      this.$MyUtils.confirm({content: '本功能依赖于您是否正确配置mysqldump的路径，确定导出菜单定义数据吗?'}).then(() => {
        exportMenuSQL({menu_id: this.menu_id}).then(res => {
          if (res.status == 200) {
            let a = document.createElement('a') //创建一个a标签
            a.href = res.data.file;
            a.download = res.data.filename;
            a.click();
            URL.revokeObjectURL(a.href); //释放之前创建的url对象
          } else {
            this.$message({message: res.msg, type: 'error'})
          }
        }).catch(() => {
        })
      }).catch(() => {
      })
    },
    // 通过数据库表生成
    createByTable() {
      if (this.tablename == '') {
        this.$message.error('请选择生成表')
      } else {
        this.$MyUtils.confirm({content: '确定生成吗?'}).then(() => {
          createByTable({
            connect: this.connect,
            table_name: this.tablename,
            page_type: 1,
            app_id: this.app_id,
            app_type: this.app_type
          }).then(res => {
            this.$message({message: '操作成功', type: 'success'})
            this.index()
          })
        }).catch(() => {
        })
      }
    },
    // 拷贝菜单
    copyMenu() {
      if (this.menu_id == '' || this.appid == '') {
        this.$message.error('请选择菜单或者应用')
      } else {
        this.$MyUtils.confirm({content: '确定复制吗?'}).then(() => {
          copyMenu({appid: this.appid, menu_id: this.menu_id}).then(res => {
            this.$message({message: '操作成功', type: 'success'})
            this.index()
          })
        }).catch(() => {
        })
      }
    },
    // 同步复制的列
    synCopy() {
      if (this.menu_id == '') {
        this.$message.error('请选择菜单')
      } else {
        this.$MyUtils.confirm({content: '同步将会把删除的列恢复，确定同步吗?'}).then(() => {
          synCopy({appid: this.app_id, menu_id: this.menu_id}).then(res => {
            this.$message({message: res.msg, type: 'success'})
            this.index()
          })
        }).catch(() => {
        })
      }
    },
    // 向导的回调
    onPageFinish() {
      localStorage.setItem('finish_api_tour', true)
    },
  },
}
</script>
<style lang="scss">
@import '@/assets/scss/common.scss';

.el-menu-tab {
  .el-menu-item {
    height: 40px;
    line-height: 40px;

    &:hover {
      // 背景色
      background-color: #fff !important;
    }
  }
}
</style>
